package com.hairline.type_handler;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * Created by fenglin on 2020/9/5 10:50 AM
 */

@MappedTypes(String[].class) //javabean中成员变量类型
@MappedJdbcTypes(JdbcType.VARCHAR) //表中某列的类型
public class SpecificationsTypeHandler extends BaseTypeHandler<String[]> {
    ObjectMapper objectMapper = new ObjectMapper();
    //输入映射的过程 → 为预编译的sql语句提供参数
    @SneakyThrows
    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int index, String[] specifications, JdbcType jdbcType) throws SQLException {
        String value = objectMapper.writeValueAsString(specifications);
        preparedStatement.setString(index,value);
    }

    //get方法 → 结果集的封装
    @SneakyThrows
    @Override
    public String[] getNullableResult(ResultSet resultSet, String columnLabel) throws SQLException {
        String result = resultSet.getString(columnLabel);
        return parseResult(result);
    }

    @SneakyThrows
    @Override
    public String[] getNullableResult(ResultSet resultSet, int index) throws SQLException {
        String result = resultSet.getString(index);
        return parseResult(result);
    }

    @SneakyThrows
    @Override
    public String[] getNullableResult(CallableStatement callableStatement, int index) throws SQLException {
        String result = callableStatement.getString(index);
        return parseResult(result);
    }

    private String[] parseResult(String result) throws JsonProcessingException {
        if (result==null){
            return null;
        }
        return objectMapper.readValue(result,String[].class);
    }
}


